package com.rongchuang.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.rongchuang.dto.PermissionDTO;
import com.rongchuang.entity.Permission;
import com.rongchuang.entity.QPermission;
import com.rongchuang.repository.PermissionRepository;
import com.rongchuang.util.ConverterUtil;
import com.rongchuang.util.DateUtils;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class PermissionService {

    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private JPAQueryFactory queryFactory;

    /**
     * 分页查询
     */
    public Page<PermissionDTO> pageSearch(int pageNum, int pageSize, String name) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        QPermission permission = QPermission.permission;
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotBlank(name)) {
            builder.and(permission.permissionName.eq(name));
        }
        List<Permission> permissionList = queryFactory
                .selectFrom(permission)
                .where(builder)
                .offset((long) pageNum * pageSize)
                .limit(pageSize)
                .orderBy(permission.id.desc())
                .fetch();
        long total = queryFactory
                .selectFrom(permission)
                .where(builder)
                .fetchCount();
        List<PermissionDTO> permissionDTOS = ConverterUtil.convertToList(permissionList, PermissionDTO.class);
        return new PageImpl<>(permissionDTOS, pageable, total);
    }

    /**
     * 保存权限信息
     */
    public void modify(PermissionDTO dto) {
        Permission entity;
        if (Objects.isNull(dto.getId())) {
            entity = ConverterUtil.convertTo(dto, Permission.class);
            entity.setCreateTime(DateUtils.getCurrentTime());
        }else {
            entity = permissionRepository.getById(dto.getId());
            if (StringUtils.isNotBlank(dto.getPermissionName())) {
                entity.setPermissionName(dto.getPermissionName());
            }
            if (StringUtils.isNotBlank(dto.getDescription())) {
                entity.setDescription(dto.getDescription());
            }
        }
        entity.setUpdateTime(DateUtils.getCurrentTime());
        permissionRepository.save(entity);
    }

    /**
     * 获取权限详情
     * @param id 权限id
     * @return 权限详情
     */
    public PermissionDTO getDetail(Long id) {
        Permission entity = permissionRepository.getById(id);
        return ConverterUtil.convertTo(entity, PermissionDTO.class);
    }
}
